﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using DatabasePluginInterface;
using QLNhaThuoc.DAL;

namespace QLNhaThuoc
{
    public partial class Form_Config : Form
    {
        public Form_Config()
        {
            InitializeComponent();
        }

        private List<IPlugin> lstPlugin;
        private string connectionString;
        private void Form_Config_Load(object sender, EventArgs e)
        {
            cboDbType.Items.Add("SQL Server");
            lstPlugin = new List<IPlugin>();
            LoadPlugins();
        }

        private void LoadPlugins()
        {
            string[] lstFile = Directory.GetFiles(Application.StartupPath + @"\Plugin\", "*.dll");

            foreach (string fileName in lstFile)
            {
                Assembly asm = Assembly.LoadFile(fileName);
                string className = fileName.Replace(Application.StartupPath + @"\Plugin\", "").Replace(".dll", "") + ".PluginForm";

                Type[] types = asm.GetTypes();
                foreach (Type t in types)
                {
                    if(t.FullName == className)
                    {
                        DatabasePluginInterface.IPlugin pluginFrm = (IPlugin)Activator.CreateInstance(t);
                        lstPlugin.Add(pluginFrm);
                        cboDbType.Items.Add(pluginFrm.GetName());
                    }
                }
            }
        }

        private void cboDbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = cboDbType.SelectedIndex;
            if(index == 0)
            {
                Form_ConfigSqlServer frm = new Form_ConfigSqlServer();
                frm.ShowDialog();
                connectionString = tbConnectionStr.Text = frm.GetConnectionString();
            }
            else
            {
                IPlugin plugin = lstPlugin[index - 1];
                plugin.ShowForm();
                connectionString = tbConnectionStr.Text = plugin.GetConnectionString();
            }
        }

        public string GetConnectionString()
        {
            return connectionString;
        }

        private void btOK_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
